<!DOCTYPE html>
<html lang="zh-Hans-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>js视差滚动</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <main class="main">
    <section class="list-item">
      <div class="item-image">
      </div>
      <div class="item-text">
        <div class="item-title">「四月是你的谎言」</div>
        <div class="item-desc">我在盛开的樱花下遇见你，从此命运不再属于自己。</div>
      </div>
    </section>

    <section class="list-item">
      <div class="item-image">
      </div>
      <div class="item-text">
        <div class="item-title">「言叶之庭」</div>
        <div class="item-desc">每晚临睡前 每天睁开眼的瞬间 不知不觉 我都在祈盼雨天 祈盼雨天 祈盼和那个人 再次相会</div>
      </div>
    </section>

    <section class="list-item">
      <div class="item-image">
      </div>
      <div class="item-text">
        <div class="item-title">「你的名字」</div>
        <div class="item-desc">黄昏，不是白昼亦不是夜晚，是我努力却看不清你的脸。</div>
      </div>
    </section>

    <section class="list-item">
      <div class="item-image">
      </div>
      <div class="item-text">
        <div class="item-title">「天气之子」</div>
        <div class="item-desc">天气真的是很不可思议，光只是天空的模样就让人感动不已。</div>
      </div>
    </section>

    <section class="list-item">
      <div class="item-image">
      </div>
      <div class="item-text">
        <div class="item-title">「K-ON！」</div>
        <div class="item-desc">重要的，珍惜的，一直在身边，一旦成为理所当然，就难以发现</div>
      </div>
    </section>

    <section class="list-item">
      <div class="item-image">
      </div>
      <div class="item-text">
        <div class="item-title">「CLANNAD」</div>
        <div class="item-desc">我也很没用，但是两个人一起的话，就会变得很坚强。</div>
      </div>
    </section>
  </main>

  <script>

    function handleScroll() {
      const imgs = document.querySelectorAll(".item-image")
      let timer = null
      return (e) => {

        if (timer === null) {
          timer = setTimeout(() => {
            // imgs.forEach(img => {
            //   console.log('offsetTop',img.getBoundingClientRect());
            // })
            /**
             * 判断元素是否在可视区
             * 当 DOMRect.top 小于视口高度 且 DOmRect.bottom 大于0
             * 当 DOMRect.left 小于视口宽度 且 DOmRect.right 大于0
             * 
            */
            imgs.forEach(img => {
              const eleRect = img.getBoundingClientRect()
              if (eleRect.top < e.target.scrollTop && eleRect.bottom > 0) {
                img.style.backgroundPosition = `center -${e.target.scrollTop * 0.02}px`
              }
            })

            timer = null
          }, 20)
        }

      }
    }
    const scrollEle = document.querySelector('body')

    scrollEle.addEventListener('scroll', handleScroll())
  </script>
</body>

</html>